﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WebHttpApi.WebHttpApi.Core;
using WebHttpApi.WebHttpApi.HttpApi;

namespace WebHttpApi
{
    /// <summary>
    /// TYPostComm 的摘要说明：第三方控阀指令请求接口
    /// </summary>
    public class TYPostComm : IHttpHandler
    {
        string str_result = "";

        public void ProcessRequest(HttpContext context)
        {
            //application/json方式：即为JSON数据，不需要检查
            context.Response.ContentType = "application/json";

            //请求主体：JSON格式字符串
            string UserName = "";
            string PassWord = "";
            string CommList = "";
            string Departmentid = "";

            Stream postData = context.Request.InputStream;
            if (postData.Length != 0)
            {
                StreamReader sRead = new StreamReader(postData);
                string postContent = sRead.ReadToEnd();

                sRead.Close();
                JObject json_post = (JObject)JsonConvert.DeserializeObject(postContent);

                UserName = json_post["UserName"].ToString();
                PassWord = json_post["PassWord"].ToString();
                CommList = json_post["CommandList"].ToString();

                if (SelectIn(UserName, PassWord, CommList))
                {
                    if (UserName == "tykj" && PassWord == "tykj@2017")
                    {
                        Departmentid = "00500";
                    }
                    else
                    {
                        Departmentid = TYMeter.DepartmentId(UserName, PassWord);
                    }
         

                    var CommResultList = new ArrayList();
                    string sql = "";
                    string sql_MeterId = "";

                    JArray meter_comm = (JArray)JsonConvert.DeserializeObject(CommList);

                    for (int i = 0; i < meter_comm.Count; i++)
                    {
                        if (sql_MeterId == "")
                        {
                            sql_MeterId = "('" + meter_comm[i]["MeterId"].ToString() + "'";
                        }
                        else
                        {
                            sql_MeterId += ",'" + meter_comm[i]["MeterId"].ToString() + "'";
                        }

                        if (i == meter_comm.Count - 1)
                        {
                            sql_MeterId += ",'" + meter_comm[i]["MeterId"].ToString() + "')";
                        }
                    }

                    sql = "select ybdz,xylx,sbdz,jcdbh from v_rp_meter_bz where ybdz in " + sql_MeterId + " and DepartmentId like '" +
                                                                                    Departmentid + "%'";

                    System.Data.DataTable Meter_Data = WebSdkCore.select(sql);

                    if (Meter_Data.Rows.Count > 0)
                    {
                        for (int i = 0; i < Meter_Data.Rows.Count; i++)
                        {
                            string Meter_ybdz = Meter_Data.Rows[i]["ybdz"].ToString();
                            string Meter_xylx = Meter_Data.Rows[i]["xylx"].ToString();

                            string Merer_sbdz = Meter_Data.Rows[i]["sbdz"].ToString();
                            string Merer_jcdbh = Meter_Data.Rows[i]["jcdbh"].ToString();

                            string str_msg = "";
                            string comm_result = "";
                            string Type = "";
                            string CommPam = "";

                            switch (Meter_xylx)
                            {
                                //NB阀控
                                case "1":
                                case "3":
                                case "6":
                                case "16":
                                case "17":                         
                                case "9":
                                    {
                                        Type = "";

                                        for (int j = 0; j < meter_comm.Count; j++)
                                        {
                                            if (meter_comm[j]["MeterId"].ToString() == Meter_ybdz)
                                            {
                                                Type = meter_comm[j]["CommandType"].ToString();
                                                CommPam = meter_comm[j]["CommandParameter"].ToString();
                                                break;
                                            }
                                        }

                                        str_msg = TyNB.Nb_Comm(Meter_xylx, Meter_ybdz, Type, CommPam);

                                        //返回
                                        if (str_msg == "成功")
                                        {
                                            comm_result = "success";
                                        }
                                        else
                                        {
                                            comm_result = "fail";
                                        }

                                        break;
                                    }

                                //NB无阀
                                case "0":
                                case "2":
                                case "5":
                                case "8":
                                //NB蓝牙
                                case "4":
                                case "7":
                                case "10":
                                //GPRS无阀
                                case "12":
                                //NB卡表
                                case "13":
                                case "14":
                                case "15":
                                    {
                                        comm_result = "not support";
                                        break;
                                    }

                                //GPRS阀控
                                case "11":
                                    {
                                        Type = "";

                                        for (int j = 0; j < meter_comm.Count; j++)
                                        {
                                            if (meter_comm[j]["MeterId"].ToString() == Meter_ybdz)
                                            {
                                                Type = meter_comm[j]["CommandType"].ToString();
                                                CommPam = meter_comm[j]["CommandParameter"].ToString();
                                                break;
                                            }
                                        }

                                        str_msg = TyGPRS.GPRS_Comm(Meter_xylx, Meter_ybdz, Type, CommPam);

                                        //返回
                                        if (str_msg == "成功")
                                        {
                                            comm_result = "success";
                                        }
                                        else
                                        {
                                            comm_result = "fail";
                                        }

                                        break;
                                    }

                                //LORA表 - 安美通
                                case "51":
                                case "52":
                                case "53":
                                    {
                                        Type = "";

                                        for (int j = 0; j < meter_comm.Count; j++)
                                        {
                                            if (meter_comm[j]["MeterId"].ToString() == Meter_ybdz)
                                            {
                                                Type = meter_comm[j]["CommandType"].ToString();
                                                CommPam = meter_comm[j]["CommandParameter"].ToString();
                                                break;
                                            }
                                        }

                                        if (Merer_sbdz != "" && Merer_jcdbh != "")
                                        {
                                            Merer_jcdbh = "0000" + Merer_jcdbh;
                                            Merer_jcdbh = Merer_jcdbh.Substring(Merer_jcdbh.Length - 4);

                                            str_msg = TyLora.Lora_Comm(Merer_sbdz, Merer_jcdbh, Meter_xylx, Meter_ybdz, Type, CommPam);

                                            //返回
                                            if (str_msg == "成功")
                                            {
                                                comm_result = "success";
                                            }
                                            else
                                            {
                                                comm_result = "fail";
                                            }
                                        }
                                        else
                                        {
                                            comm_result = "Incomplete information";
                                        }

                                        break;
                                    }

                                //RTU + 超声水表 数据监控：控阀
                                case "201":
                                case "202":
                                    {
                                        string Device_sql = "select sbdz,sblx from rp_device_bz where sbdz='" +
                                                        Merer_sbdz + "'";

                                        System.Data.DataTable Device_Data = WebSdkCore.select(Device_sql);

                                        if (Device_Data.Rows.Count > 0)
                                        {
                                            string Device_xylx = Device_Data.Rows[0]["sblx"].ToString();

                                            str_msg = TyRTU.Rtu_Comm(Device_xylx, Meter_ybdz, Merer_sbdz, "7", CommPam);

                                            //返回
                                            if (str_msg == "成功")
                                            {
                                                comm_result = "success";
                                            }
                                            else
                                            {
                                                comm_result = "fail";
                                            }
                                        }
                                        else
                                        {
                                            comm_result = "Unregistered device";
                                        }

                                        break;
                                    }

                            }
                            CommResultList.Add(new
                            {
                                MeterId = Meter_ybdz,
                                CommandType = Type,
                                CommandParameter = CommPam,
                                CommandResult = comm_result,
                            }
                            );
                        };
                        var json_result = new
                        {
                            status = "success",
                            CommandResultList = CommResultList,
                        };
                        str_result = WebSdkCore.ToJSON(json_result);
                    }
                    else
                    {
                        var json_result = new
                        {
                            status = "success",
                            message = "No data",
                        };
                        str_result = WebSdkCore.ToJSON(json_result);
                    }
                }
                else
                {
                    var json_result = new
                    {
                        status = "error",
                        message = "Missing parameter",
                    };
                    str_result = WebSdkCore.ToJSON(json_result);
                }
            }
            else
            {
                var json_result = new
                {
                    status = "error",
                    message = "Missing parameter",
                };
                str_result = WebSdkCore.ToJSON(json_result);
            }
            context.Response.Write(str_result);
        }
        
        public static bool SelectIn(string UserName, string PassWord, string CommList)
        {
            bool result;
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord) || string.IsNullOrEmpty(CommList))
            {
                result = false;
            }
            else
            {
                result = true;
            }
            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}